#include "xiostream.h"
#include <iostream>

void XIOStream::start()
{
    th_ = std::thread(&XIOStream::handle, this);
}

void XIOStream::wait()
{
    if (th_.joinable()) {
        th_.join();
    }
}

void XIOStream::stop()
{
    isExit_ = true;
}

void XIOStream::setNext(std::shared_ptr<XIOStream> next)
{
    next_ = next;
}

void XIOStream::push(std::shared_ptr<XData> data)
{
    std::unique_lock<std::mutex> lock(mutex_);
    notFull_.wait(lock, [this] {
        return datas_.size() <= maxDatasSize;
    });
    datas_.push_back(data);
    notEmpty_.notify_one();
}

std::shared_ptr<XData> XIOStream::pop()
{
    std::unique_lock<std::mutex> lock(mutex_);
    notEmpty_.wait(lock, [this](){
        return !datas_.empty();
    });
    auto ret = datas_.front();
    datas_.pop_front();
    notFull_.notify_one();
    
    return ret;
}

void XIOStream::setMemPool(std::shared_ptr<std::pmr::memory_resource> pool)
{
    memPool_ = pool;
}

XIOStream::~XIOStream()
{
    //std::cout << __FUNCTION__ << std::endl;
}